package com.cens.mall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.cens.common.to.mq.OrderTo;
import com.cens.common.to.mq.StockLockedTo;
import com.cens.common.utils.R;
import com.cens.mall.ware.entity.WareOrderTaskDetailEntity;
import com.cens.mall.ware.entity.WareOrderTaskEntity;
import com.cens.mall.ware.service.WareSkuService;
import com.cens.mall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import lombok.AllArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@AllArgsConstructor
@RabbitListener(queues = "stock-release-stock-queue")
public class StockReleaseListener {

    @Autowired
    private final WareSkuService wareSkuService;


    /**
     * 库存自动解锁
     *  手动ack
     * @param stockLockedTo
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleStockRelease(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
        try {
            wareSkuService.unlockStock(stockLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @RabbitHandler
    public void handleOrderClose(OrderTo orderTo,Message message, Channel channel) throws IOException {
        try{
            System.out.println("order close  ...");
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

}
